package net.tavion.angelboot.fegin.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import net.tavion.angelboot.common.utils.JudgeUtils;
import net.tavion.angelboot.fegin.logger.AccessLogger;
import net.tavion.angelboot.fegin.logger.RequestInfo;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Configuration
@Slf4j
public class FeginRequestInterceptor implements RequestInterceptor {
  private static final String JOIN_CHAR = "&";
  private static final String QUERY_KEY = "query";
  private static final String BODY_KEY = "body";
  private AccessLogger accessLogger;
  private ObjectMapper objectMapper;

  public FeginRequestInterceptor(AccessLogger accessLogger, ObjectMapper objectMapper) {
    this.accessLogger = accessLogger;
    this.objectMapper = objectMapper;
  }

  @Override
  public void apply(RequestTemplate template) {
    RequestInfo<Object> requestInfo = RequestInfo.builder().uri(template.url()).appName("Appname").token("x-token").loginName("loginName").target(this.target(template)).build();
    this.accessLogger.request(requestInfo);
  }

  private Object target(RequestTemplate template) {
    if (JudgeUtils.isNullAny(new Object[]{template.body(), Optional.ofNullable(template.queries()).filter((s) -> {
      return !s.isEmpty();
    }).orElse((Map)null)})) {
      if (template.body() != null) {
        return this.bodyString(template.body());
      } else {
        return template.queries() != null && !template.queries().isEmpty() ? template.queries().entrySet() : "";
      }
    } else {
      Map<String, Object> map = new HashMap();
      map.put("query", template.queries().entrySet());
      map.put("body", this.bodyString(template.body()));
      return map;
    }
  }

  private Object bodyString(byte[] body) {
    try {
      return this.objectMapper.readValue(body, Map.class);
    } catch (Exception var3) {
      return "";
    }
  }

  private String queryString(Map<String, Collection<String>> queries) {
    StringBuilder log = new StringBuilder();
    queries.entrySet().stream().forEach((e) -> {
      if (log.length() != 0) {
        log.append("&");
      }

      log.append((String)e.getKey()).append("=").append(e.getValue());
    });
    return log.toString();
  }
}